import { BasicDrawer, useDrawerInner } from "@/components/Drawer";
import { BasicForm, FormSchema, useForm } from "@/components/Form";
import { useMemo, useState } from "react";

const DetailDrawer = (props: { register: Fn }) => {
	const formSchema: FormSchema[] = [
		{
			label: "number of times",
			field: "time",
			component: "Input"
		},
		{
			label: "Type",
			field: "type",
			component: "Select",
			componentProps: {
				options: [
					{
						label: "Admitted",
						value: 1
					},
					{
						label: "Outpatient",
						value: 2
					}
				]
			}
		},
		{
			label: "Patient Type",
			field: "patientType",
			component: "Select",
			componentProps: {
				options: [
					{
						label: "Health Insurance",
						value: 1
					},
					{
						label: "Service Fee",
						value: 2
					},
					{
						label: "Health Insurance - HD 52",
						value: 3
					},
					{
						label: "Service Fee - TT 02",
						value: 4
					}
				]
			}
		},
		{
			label: "Content",
			field: "content",
			component: "Input"
		},
		{
			label: "Amount",
			field: "amount",
			component: "Input"
		}
	];
	const [registerForm, { resetFields, setFieldsValue, validateFields }] = useForm({
		labelWidth: 100,
		schemas: formSchema,
		baseColProps: { span: 24 }
	});

	const [isUpdated, setIsUpdated] = useState(false);
	const getTitle = useMemo(() => {
		return isUpdated ? "Edit medical record status" : "Add medical record status";
	}, [isUpdated]);

	const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(props.register, data => {
		resetFields();
		setDrawerProps({ confirmLoading: true });
		setIsUpdated(!!data?.isUpdated);
		setFieldsValue({
			...data.record
		});
		setDrawerProps({ confirmLoading: false });
	});

	const handleSubmit = async () => {
		try {
			const values = await validateFields();
			console.log("values", values);
			setDrawerProps({ confirmLoading: true });
			closeDrawer();
		} finally {
			setDrawerProps({ confirmLoading: false });
		}
	};

	return (
		<BasicDrawer {...props} title={getTitle} register={registerDrawer} showFooter={true} ok={handleSubmit}>
			<BasicForm register={registerForm}></BasicForm>
		</BasicDrawer>
	);
};

export default DetailDrawer;
